package org.jsbd.boss.action;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.domian.UpgradeApkBean;
import org.jsbd.boss.service.IUpgradeApkService;
import org.jsbd.boss.util.CacheKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/upgrade")
public class UpgradeApkController {

	private static final Logger logger = LoggerFactory.getLogger(UpgradeApkController.class);

	@Resource
	private IUpgradeApkService upgradeApkService;
	@Resource
	private RedisClient redisClient;

	@ResponseBody
	@RequestMapping(value = "/package")
	public Map<String, Object> getUpgradeInfo(String mark, String version) {
		Integer sourceVersion = Integer.valueOf(version);
		// 校验版本
		Integer targetVersion = 0;
		Object tv = redisClient.get(CacheKey.UPGRADE_VERSION + "_" + mark);
		if (null == tv) {
			UpgradeApkBean uab = upgradeApkService.getByMark(mark);
			targetVersion = Integer.valueOf(uab.getVersion());
			redisClient.put(CacheKey.UPGRADE_VERSION + "_" + mark, targetVersion);
		} else {
			targetVersion = (Integer) tv;
		}
		
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("code", 0);
		result.put("msg", "该mark" + mark + "无任务！");

		if (sourceVersion < targetVersion) {
			Object obj = redisClient.evalHget(CacheKey.UPGRADE_APK_INDEX, mark);
			if (null == obj || Integer.valueOf(String.valueOf(obj)) <= 0) {
				return result;
			} 
			UpgradeApkBean uab  = (UpgradeApkBean) redisClient.hget(CacheKey.UPGRADE_APK_DATA, mark);
			if (null == uab) {
				uab = upgradeApkService.getByMark(mark);
				redisClient.hset(CacheKey.UPGRADE_APK_DATA, mark, uab);
				redisClient.evalHincrby(CacheKey.UPGRADE_APK_INDEX, mark, -1);
			} else {
				redisClient.evalHincrby(CacheKey.UPGRADE_APK_INDEX, mark, -1);
			}
			
			result.put("code", 1);
			result.put("msg", "请求成功！");
			result.put("data", uab);
		} 
		
		return result;
	}

}
